import os

from apscheduler.schedulers.blocking import BlockingScheduler

from aop.aop_config import load_global_config
from sync.sync_order import main as sync_order_main
from sync.sync_order_goods import main as sync_order_goods_main
from sync.sync_order_goods_tb import main as sync_order_goods_tb_main
from sync.sync_order_tb import main as sync_order_tb_main
from sync.sync_ordered_bidding import main as sync_ordered_bidding_main
from sync.sync_outer_goods import main as sync_outer_goods_main
from sync.sync_outer_goods_sku import main as sync_outer_goods_sku_main
from sync.sync_outer_goods_sku_log import main as sync_outer_goods_sku_log_main
from sync.sync_z_after_all_synced import update as sync_z_after_all_synced_update
from utils.date_tuils import get_minutes_to_time
from utils.log_utils import get_logger

# 获取一个命名的日志记录器
logger = get_logger(__name__, os.path.splitext(os.path.basename(__file__))[0])


def job(h=7, m=0):
    hour, minute = h, m
    # 任务列表中的数字,代表此任务相对于上一条任务的偏移量
    tasks = [
        (sync_order_main, 'sync_order_main', 0),  # 这一条,数字 0 代表相对于配置文件中指定时间偏移量
        (sync_order_goods_main, 'sync_order_goods_main', 5),  # 数字 2 代表相对于 上一条任务的时间偏移量,后面任务也是
        (sync_order_goods_tb_main, 'sync_order_goods_tb_main', 5),
        (sync_order_tb_main, 'sync_order_tb_main', 5),
        (sync_outer_goods_main, 'sync_outer_goods_main', 5),
        (sync_outer_goods_sku_main, 'sync_outer_goods_sku_main', 5),
        (sync_ordered_bidding_main, 'sync_ordered_bidding_main', 5),  # 这个执行的较长,下一个任务与这个任务可拉开距离
        (sync_outer_goods_sku_log_main, 'sync_outer_goods_sku_log_main', 10),
        (sync_z_after_all_synced_update, 'sync_z_after_all_synced_update', 2)
    ]

    for task_func, task_name, offset in tasks:
        hour, minute = get_hm(hour, minute, offset)
        register_job(task_func, hour, minute, task_name)


def register_job(worker, hour, minute, task_id=None):
    logger.info("注册执行任务: %s ,执行时间为每天 %02d:%02d", task_id, hour, minute)
    scheduler.add_job(
        worker,
        'cron',
        hour=hour,
        minute=minute,
        id=task_id,
        misfire_grace_time=60,  # 允许最多延迟 60 秒执行
        coalesce=False
    )


def get_hm(hour, minute, offset=5):
    """

    :param hour: 定时任务执行的时间点,小时
    :param minute: 定时任务执行的时间点,分钟
    :param offset: 向后偏移多少分钟
    :return:
    """
    h, m = get_minutes_to_time(hour=hour, minutes=minute, offset=offset)
    return h, m


@load_global_config('../config/config.json5')
def main():
    global scheduler
    scheduler = BlockingScheduler()
    from config.config import CONFIG
    start_time_hour = CONFIG.get('cron')['start_time_hour']
    start_time_minute = CONFIG.get('cron')['start_time_minute']
    job(start_time_hour, start_time_minute)
    scheduler.start()


if __name__ == '__main__':
    global scheduler
    main()
